-- UISkyCityExploreShop
-- Create by chendh
-- 天空探索特殊商店界面

-- UISkyCityExploreShop继承自Layer
UISkyCityExploreShop = class("UISkyCityExploreShop", function()
    return cc.Layer:create();
end);

function UISkyCityExploreShop.create(exploreIndex)
    return UISkyCityExploreShop.new(exploreIndex);
end

-- 商品格最大行数和列数
local MAX_GRID_ROW    = 2;
local MAX_GRID_COLUMN = 3;

-- 内部函数声明

-- 构造函数
function UISkyCityExploreShop:ctor(exploreIndex)
    -- 初始化
    self:setName("UISkyCityExploreShop");
    local node = cc.CSLoader:createNode("layout/shop/BlackMarket.csb");
    self:addChild(node);
    self.node = node;

    self.exploreIndex = exploreIndex;
    local skyExplore = ME.user.dbase:query("sky_explore", {});
    local exploreInfo = skyExplore[exploreIndex];
    self.exploreInfo = exploreInfo;
    self.triggerId = exploreInfo["trigger_id"];

    local CT = node:getChildByName("CT");
    local scrollview = CT:getChildByName("scroll_view");
    self.CT = CT;
    self.scrollView = scrollview;
    self.scrollView:setVisible(true);

    -- 水平滑动，需要显示左右蒙版
    local mask3 = findChildByName(self.node, "CT/mask3");
    mask3:setVisible(true);
    local mask4 = findChildByName(self.node, "CT/mask4");
    mask4:setVisible(true);

    -- 修改滚动方向
    -- 1 垂直
    -- 2 水平
    self.scrollView:setDirection(2);

    -- 尝试请求次数
    self.hasTry = 0;

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化数据
    self:gatherGoodsInfo();
    -- 初始化商品格子
    self:initGoodsGrids(self.node);

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UISkyCityExploreShop:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 初始化商品格
function UISkyCityExploreShop:initGoodsGrids(node)
    local w = DESIGN_WIDTH;
    local h = DESIGN_HEIGHT;

    -- 图标间距(横向)
    local wGap = 23;

    -- 图标间距(纵向)
    local hGap = 33;

    -- 图标宽度
    local iconWidth = 128;

    -- 图片高度
    local iconHeight = 163;

    local topHGap  = 100;
    local leftWGap = 20;

    -- 收集商品信息
    local goodsList = self.data;

    -- 商品的共个数
    local shopCount = #goodsList;

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/shop/BlackMarketGoodsIcon.csb");
    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param maxRowNum     最大行数
    -- @param pageColNum    单页可以显示下的列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    initScrollGridsHorizontal(self, self.scrollView, itemNode, shopCount, MAX_GRID_ROW, MAX_GRID_COLUMN, wGap, hGap, iconWidth, iconHeight, topHGap, leftWGap, self.registerItemTouchEvent);
end

-- 清空所有的商品格
function UISkyCityExploreShop:clearAllGrid()
    -- 格子总数
    local totalGridCount = #self.data;
    for i = 1, totalGridCount do
        local grid = self.scrollView:getChildByName("item" .. i);
        if grid then
            grid:setVisible(false);
        end
    end
end

-- 显示商店
function UISkyCityExploreShop:redraw()
    local triggerId = self.triggerId;
    local eventInfo = SkyExploreTriggerM.query(triggerId);

    -- 显示标题
    local titleLabel = findChildByName(self.CT, "title");
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(eventInfo["name"]);

    local subheadLabel = findChildByName(self.CT, "subhead");
    TextStyleM.setSubheadStyle(subheadLabel);
    subheadLabel:setString(getLocStr("choose_goods"));

    -- 收集商品信息
    local goodsList = self.data;

    if not goodsList or #goodsList == 0 then
        cclog("收集商品信息失败。");
        self:clearAllGrid();
        return;
    end

    -- 显示商品信息
    local totalGoodsCount = #goodsList;
    for i = 1, totalGoodsCount do
        local grid          = self.scrollView:getChildByName("item" .. i);
        local goodsBg       = grid:getChildByName("bg");
        local iconImg       = grid:getChildByName("goods_icon");
        local moneyImg      = grid:getChildByName("money_icon");
        local moneyLabel    = grid:getChildByName("money_count");
        local soldOutLabel    = grid:getChildByName("sold_out");
        local rankNode      = grid:getChildByName("star_node");
        local countLabel     = grid:getChildByName("item_count");

        local goodsIndex = goodsList[i][1]    -- 商品序号
        local goodsId    = goodsList[i][2];   -- 商品id
        local classId    = goodsList[i][3];   -- 道具id
        local goodsIcon  = goodsList[i][4];   -- 商品图标
        local goodsCount = goodsList[i][5];   -- 商品数量
        local goodsPrice = goodsList[i][6];   -- 商品价格
        local itemName   = goodsList[i][7];   -- 物品名称
        local itemDesc   = goodsList[i][8];   -- 物品描述
        local soldOut    = goodsList[i][9];   -- 是否售完
        local rank       = goodsList[i][10];  -- 阶位

        -- 为商品图标绑定信息
        iconImg.goodsIndex = goodsIndex;
        iconImg.goodsId    = goodsId;
        iconImg.classId    = classId;
        iconImg.goodsIcon  = goodsIcon;
        iconImg.goodsCount = goodsCount;
        iconImg.goodsPrice = goodsPrice;
        iconImg.itemName   = itemName;
        iconImg.itemDesc   = itemDesc;
        iconImg.soldOut    = soldOut;
        iconImg.rank       = rank;

        -- 显示商品阶位
        -- 目前不显示阶位
        rankNode:setVisible(false);
        --[[local layer = createStarLayer(rank, "images/ui/symbol/star_little.png", "center", -0.7);
        if layer then
            rankNode:removeAllChildren();
            rankNode:addChild(layer);
        end]]

        -- 显示商品名称和数量
        TextStyleM.setTextStyle(countLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -2);
        if goodsCount > 1 then
            -- 需要显示数量
            countLabel:setString(tostring(goodsCount));
        else
            countLabel:setVisible(false);
        end

        -- 显示商品图标
        iconImg:loadTexture(getItemIconPath(goodsIcon));

        -- 显示价格
        local offset = 0;
        local iconPath;

        -- 属性支付
        local payType = goodsPrice[1];
        local payAttrib = goodsPrice[2];
        local payNum = goodsPrice[3];
        if 2 == payType then
            iconPath = getSmallAttribIconPath(FieldsM.query(payAttrib, "icon"));
            moneyImg:loadTexture(iconPath);
            if payAttrib == "money" then
                moneyImg:setScale(0.74);
                offset = -5;
            else
                moneyImg:setScale(0.55);
            end
        elseif 1 == payType then
            -- 物品支付
            iconPath = getItemIconPath(ItemM.query(payAttrib, "icon"));
            moneyImg:setScale(0.45);
            moneyImg:loadTexture(iconPath);
        end

        TextStyleM.setTextStyle(moneyLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_WHITE, true);
        moneyLabel:setString(tostring(payNum));
        moneyLabel:getVirtualRenderer():setAdditionalKerning(getLocKerning() -3);

        if 2 == payType then
            if ME.user:queryAttrib(payAttrib) < payNum then
                moneyLabel:setTextColor(TextStyleM.TEXT_COLOR_LIGHT_RED);
            else
                moneyLabel:setTextColor(TextStyleM.TEXT_COLOR_WHITE);
            end
        else
            if ItemM.getAmount(ME.user, payAttrib) < payNum then
                moneyLabel:setTextColor(TextStyleM.TEXT_COLOR_LIGHT_RED);
            else
                moneyLabel:setTextColor(TextStyleM.TEXT_COLOR_WHITE);
            end
        end

        -- 居中显示
        local moneyImgW = moneyImg:getContentSize().width * moneyImg:getScaleX();
        local moneyLabelW = moneyLabel:getContentSize().width;
        -- 间隔
        local gap = 5;
        local s = (moneyImgW + moneyLabelW + gap) / 2;
        -- 位置调整
        moneyImg:setPositionX(-s - offset / 2 );
        moneyLabel:setPositionX(moneyImg:getPositionX() + offset + moneyImgW + gap);

        -- 如果商品已售完，显示图标
        if soldOut then
            -- 背景变灰
            setGrayTransMode(goodsBg, true);
            setGrayTransMode(iconImg, true);

            -- 不显示价格、星星
            moneyImg:setVisible(false);
            moneyLabel:setVisible(false);
            rankNode:setVisible(false);

            -- 显示已出售字样
            soldOutLabel:setVisible(true);
            TextStyleM.setTextStyle(soldOutLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_ORANGE, true);
            soldOutLabel:getVirtualRenderer():setAdditionalKerning(getLocKerning() -3);
            soldOutLabel:setString(getLocStr("has_been_sold"));
        else
            -- 背景变亮
            setGrayTransMode(goodsBg, false);
            setGrayTransMode(iconImg, false);

            -- 显示图标、价格、星星
            moneyImg:setVisible(true);
            moneyLabel:setVisible(true);
            rankNode:setVisible(true);

            soldOutLabel:setVisible(false);
        end

    end
end

-- 获取可购买的商品信息
function UISkyCityExploreShop:gatherGoodsInfo()
    -- 获取本店的所有商品
    local goodsList = self.exploreInfo["goods"];
    if goodsList == nil then
        self.data = nil;
        return;
    end

    local ret = {};
    local index;  -- 商品的序号
    for index, id in pairs(goodsList) do
        local info = SkyExploreShopM.query(id);
        local goodsInfo = info["goods"];
        local soldOut    = table.indexOf(self.exploreInfo["sold"] or {}, index) >= 1;
        local classId    = goodsInfo[2];
        local goodsCount = goodsInfo[3];      -- 商品数量
        local goodsType  = goodsInfo[1];

        local itemInfo = ItemM.query(classId);

        if itemInfo then
            table.insert(ret, {index, id, classId, itemInfo["icon"], goodsCount, info["price"],
                itemInfo["name"], itemInfo["desc"], soldOut, itemInfo["rank"]});
        end
    end

    self.data = ret;
end

-- 注册商品点击事件
function UISkyCityExploreShop:registerItemTouchEvent(node)
    -- 注册商品图标点击事件
    local image = node:getChildByName("bg");
    local iconImg = node:getChildByName("goods_icon");
    local function onClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 仅处理非空的格子
            if type(iconImg.goodsIcon) == 'number' then
                self:onGoodsClick(iconImg);
                AudioM.playFx("button_spell");
            end
        end
    end
    image:addTouchEventListener(onClick)
end

-- 注册事件处理回调函数
function UISkyCityExploreShop:registerEventCallback()

    -- 关注购买商品的事件
    EventMgr.register("UISkyCityExploreShop", event.SKY_EXPLORE_SHOP_BUY, function(args)
        local result = args.result;
        local exploreIndex = args.exploreIndex;
        local index = args.index;

        if result == 0 then
            -- 购买失败
        else
            self:whenBuyGoods(exploreIndex, index);
        end
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UISkyCityExploreShop", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UISkyCityExploreShop" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_FIRST_RUINS_SCRAP, TOPMENU_FRAME_GEM, TOPMENU_FRAME_HEAD_AIRSHIP);
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UISkyCityExploreShop");
        end
    end);
end

-- 注册点击事件
function UISkyCityExploreShop:registerTouchEvent()
    -- 注册刷新按钮点击事件
    local btnRefresh = findChildByName(self.node, "BT/refresh");
    btnRefresh:setVisible(false);

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("ship_return");
            UIMgr.getCurrentScene():removeFormByName("UISkyCityExploreShop");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 当商品被点击
function UISkyCityExploreShop:onGoodsClick(iconImg)
    if iconImg.soldOut then
        alert(getLocStr("goods_sold_out"));
        return;
    end

    -- 显示商品详细信息
    require "game/ui/form/sky_city/UISkyCityExploreShopGoodsInfo"
    local uiGoodsDetail = UISkyCityExploreShopGoodsInfo.create(self.exploreIndex, iconImg.goodsIndex);
    UIMgr.getCurrentScene():addForm(uiGoodsDetail);
end

-- 关闭购买商品的消息
function UISkyCityExploreShop:whenBuyGoods(exploreIndex, index)

    if self.exploreIndex ~= exploreIndex then
        return;
    end

    local goodsInfo = self.data[index];
    local name = goodsInfo[7];
    local count = goodsInfo[5];
    goodsInfo[9] = true;

    -- 提示玩家购买了商品
    alert(string.format(getLocStr("buy_goods_done"), name, count));

    -- 刷新界面
    self:redraw();
end